import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        List<Integer> list = null;
        Arrays.sort(nums);
        int n = nums.length;
        for(int c = n - 1; c >= 2; c--) {
            int left = 0, right = c-1;
            while(left < right) {
                if(nums[left] + nums[right] < -nums[c]) {
                    left++;
                }else if(nums[left] + nums[right] > -nums[c]) {
                    right--;
                }else {
                    list = new ArrayList<>();
                    list.add(nums[left]);
                    list.add(nums[right]);
                    list.add(nums[c]);
                    ret.add(list);
                    while(nums[left] == nums[left+1] && left < right) {
                        left++;
                    }
                    left++;
                    while(nums[right] == nums[right-1] && left < right) {
                        right--;
                    }
                    right--;
                }
            }
            while(nums[c] == nums[c-1] && c >= 2) {
                c--;
            }
        }
        return ret;
    }
}
